<template>
  <div class="city-container">
    <div class="tar-bar">
      <div class="back" @click="$router.back()">
        <!-- 返回箭头 -->
        <div class="icon">
          <img src="@/assets/arrow/c4.png" alt="" />
        </div>
      </div>
      <!-- 选择国内还是国外 -->
      <div class="option">
        <span class="domestic" :class="{ active: option == 'domestic' }" @click="toggleOption('domestic')">国内</span>
        <span class="international" :class="{ active: option == 'international' }" @click="toggleOption('international')">国际</span>
      </div>
      <div class="empty"></div>
    </div>
    <!-- 搜索城市 -->
    <van-search v-model="value" placeholder="请输入城市名称" background="#d8d8d8" @input="sendSearch" />

    <!-- 搜索之后展示的城市 -->
    <div class="filter-city-list" v-if="value != ''">
      <div class="filter-city-item" v-for="(c, i) in filterCity" :key="i" @click="setCity(c)">{{ c }}</div>
    </div>

    <!-- 定位城市 -->
    <div class="location-box" v-if="value == ''">
      <div class="title">定位城市</div>
      <div class="city" @click="setCity({ name: $store.state.city })">
        {{ $store.state.city }}
      </div>
    </div>
    <!-- 热门城市 -->
    <div class="hot-city" v-if="value == ''">
      <div class="title">热门城市</div>
      <div class="hot-city-list">
        <div class="hot-city-item" v-for="(c, i) in hotCityList" :key="i" @click="setCity(c)">{{ c.name }}</div>
      </div>
    </div>
    <!-- 所有城市 -->
    <van-index-bar :index-list="indexList" :sticky-offset-top="50" highlight-color="#D94648" v-if="value == ''">
      <van-index-anchor index="A" />
      <van-cell :title="c.name" v-for="c in allCity['A']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="B" />
      <van-cell :title="c.name" v-for="c in allCity['B']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="C" />
      <van-cell :title="c.name" v-for="c in allCity['C']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="D" />
      <van-cell :title="c.name" v-for="c in allCity['D']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="E" />
      <van-cell :title="c.name" v-for="c in allCity['E']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="F" />
      <van-cell :title="c.name" v-for="c in allCity['F']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="G" />
      <van-cell :title="c.name" v-for="c in allCity['G']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="H" />
      <van-cell :title="c.name" v-for="c in allCity['H']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="I" />
      <van-cell :title="c.name" v-for="c in allCity['I']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="J" />
      <van-cell :title="c.name" v-for="c in allCity['J']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="K" />
      <van-cell :title="c.name" v-for="c in allCity['K']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="L" />
      <van-cell :title="c.name" v-for="c in allCity['L']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="M" />
      <van-cell :title="c.name" v-for="c in allCity['M']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="N" />
      <van-cell :title="c.name" v-for="c in allCity['N']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="O" />
      <van-cell :title="c.name" v-for="c in allCity['O']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="P" />
      <van-cell :title="c.name" v-for="c in allCity['P']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="Q" />
      <van-cell :title="c.name" v-for="c in allCity['Q']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="R" />
      <van-cell :title="c.name" v-for="c in allCity['R']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="S" />
      <van-cell :title="c.name" v-for="c in allCity['S']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="T" />
      <van-cell :title="c.name" v-for="c in allCity['T']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="U" />
      <van-cell :title="c.name" v-for="c in allCity['U']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="V" />
      <van-cell :title="c.name" v-for="c in allCity['V']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="W" />
      <van-cell :title="c.name" v-for="c in allCity['W']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="X" />
      <van-cell :title="c.name" v-for="c in allCity['X']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="Y" />
      <van-cell :title="c.name" v-for="c in allCity['Y']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="Z" />
      <van-cell :title="c.name" v-for="c in allCity['Z']" :key="c.name" @click="setCity(c)" />
      <van-index-anchor index="#" />
      <van-cell :title="c.name" v-for="c in allCity['#']" :key="c.name" @click="setCity(c)" />
    </van-index-bar>
  </div>
</template>

<script>
import axios from '@/utils/request'
export default {
  data() {
    return {
      value: '',
      type: 0,
      option: 'domestic',
      hotCityList: [],
      allCity: {},
      timer: null, // 定时器，节流
      filterCity: [], // 搜索出来的城市
      indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#']
    }
  },
  methods: {
    //热门搜索城市
    async requestHotCity() {
      /*
      请求接口：https://api.xmonster.cn/v2/cities/hot
      请求方式：get
      请求参数：
      params:{
        type: 0（国内） 1（国外）
      }
      */
      const data = await axios.get('/v2/cities/hot', {
        params: {
          type: this.type
        }
      })
      if (data.length > 0) {
        this.hotCityList = data
      }
      console.log(data)
    },
    // 请求所有城市名称
    async requestCityList() {
      /*
      请求地址：https://api.xmonster.cn/v2/cities/all_list
      请求方法：get
      请求参数：
      params：{
        type： 0（国内） 1（国外）
      }
      */
      const data = await axios.get('/v2/cities/all_list', {
        params: {
          type: this.type
        }
      })
      if (data.length > 0) {
        data.forEach((c) => {
          if (this.indexList.indexOf(c.h) < 0) {
            if (this.allCity['#']) {
              this.allCity['#'].push(c)
            } else {
              this.$set(this.allCity, '#', [c])
            }
          } else if (c.h in this.allCity) {
            this.allCity[c.h].push(c)
          } else {
            this.$set(this.allCity, c.h, [c])
          }
        })
      }
    },
    //切换option
    async toggleOption(val) {
      if (val == this.option) return
      this.option = val
      if (val == 'domestic') {
        this.type = 0
      } else {
        this.type = 1
      }
      await this.sendRequest()
      if (this.value != '') {
        this.sendSearch()
      }
    },
    sendSearch() {
      if (this.value == '') return
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.filterCity = []
        for (let key in this.allCity) {
          this.allCity[key].forEach((c) => {
            if (c.name.indexOf(this.value) > -1) {
              this.filterCity.push(c)
            }
          })
        }
      }, 500)
    },
    async sendRequest() {
      this.hotCityList = []
      this.allCity = {}
      const Toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '加载中...'
      })
      this.requestHotCity()
      await this.requestCityList()
      Toast.clear()
    },
    setCity(city) {
      console.log(city)
      this.$store.commit('setCity', city)
      this.$router.back()
    }
  },
  created() {
    this.sendRequest()
  }
}
</script>

<style lang="less" scoped>
.city-container {
  padding-top: 50px;

  .tar-bar {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10;
    height: 50px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #d94648;

    & > div {
      height: 36px;
    }

    .back {
      padding-left: 10px;
      display: flex;
      align-items: center;

      .icon {
        transform: rotate(180deg);
        height: 18px;
        width: 18px;
        img {
          height: 100%;
          width: 100%;
        }
      }
    }

    .option {
      display: flex;
      color: #c1c1c1;
      align-items: center;
      height: 30px;
      border: 1px solid #ccc;
      border-radius: 5px;

      span {
        line-height: 30px;
      }

      .domestic {
        padding: 0 10px 0 20px;
        height: 100%;
      }

      .international {
        padding: 0 20px 0 10px;
        height: 100%;
      }

      .active {
        color: #fff;
        background-color: rgba(255, 255, 255, 0.5);
      }
    }

    .empty {
      width: 50px;
    }
  }
  ::v-deep .van-search__content {
    border-radius: 5px;
  }
  .location-box,
  .hot-city,
  .filter-city-list {
    .title {
      font-size: 14px;
      color: #000;
      font-weight: 700;
      padding: 9px 16px;
      background-color: #f0f0f0;
    }
    .city,
    .hot-city-item,
    .filter-city-item {
      color: #323232;
      font-size: 14px;
      padding: 10px 16px;
      border-bottom: 1px solid #eee;
    }
  }

  ::v-deep .van-index-anchor {
    color: #000;
    font-weight: 700;
    background-color: #f0f0f0;
  }
}
</style>
